define(function(require){
	var main =require('/static/main.js');
	var m = new main();
	function Cont(){
		this.Fun._init();
	}
	Cont.prototype.Fun = {
		TagIds:[],
		_init:function(){
			this.getSign();
			this.getGroup(); //获取分组列表
			this.bindEvent();
		},
		// 获取右边分组列表
		getGroup:function(){
			$.ajax({
                type: "POST",
                url: "/customer/group-list",
                dataType: "json",
				success:function (ret) {
	               if(ret.IsBizSuccess){
	               		var str = '<li class="active getlistid"><a href="#v-home" data-toggle="tab" aria-expanded="true" data-index="0" data-id="" style="border-top:0px!important;">全部客户</a></li>';
	               		var option = '<option value="0">添加到分组</option>';
	               		ret.Models.forEach(function(v,k){
	               			option += '<option value="'+v.GroupId+'">'+v.GroupName+'</option>'
	               			str += ' <li class="getlistid"><a href="#v-profile" data-toggle="tab" aria-expanded="false" data-index="'+(k+1)+'" data-id="'+v.GroupId+'">'+v.GroupName+'</a></li> ';
	               		})
	               		str+='<li class="lastTab " data-toggle="modal" id="AddGroup" >添加分组</li>';
	               		$('.w-tabs-vertical').html(str);
	               		$('.getGroup').html(option);
	               		$('#chose_group').html(option);

	               }
	            }
        	})
		},
		getSign:function(){
			$.ajax({
                type: "POST",
                url: "/customer/sign-list",
                dataType: "json",
                success: function (ret) {
            	   var str = '';
            	   if(ret.Models.length > 0){
        	   			$.each(ret.Models,function(k,v){
	            	   		str+='<span class="Label_btnspan" data-id="'+v.TagId+'" data-name="'+v.TagName+'">'+v.TagName+'</span>'
	            	    })
	            	    str+='<span class="Label_btnadd" data-dismiss="modal">添加标签</span>'
            	   }else{
            	   		// $('.Label_btn').css({'text-align':'center'})
            	   		// str+='暂无标签'
            	   }
            	   	   $('.Label_btn').html(str);
                }
            });
		},
		bindEvent:function(){
			var _this = this;
			// 添加标签
	        $(document).on('click','.Label_btnadd',function(){
				var index = layer.prompt({
				       title : '标签名称：'
				},function(val, index){
					  if(val.length > 10){
					  	layer.msg('标签名称不能大于10个字');
					  	layer.close(index);
					  	return false;
					  }else{
					      var data = {
					      	TagName:val,
					      }
					      $.ajax({
	                		type: "POST",
							url:'/customer/sign-add',
							data:data,
							dataType: "json",
							success:function (ret) {
				               if(ret.IsBizSuccess){
				               		layer.msg('添加成功');
				               		_this.getSign();
					     			layer.close(index);
				               }else{
				               		layer.msg('添加失败');
					     			layer.close(index);
				               }
				            }
			        	 })
					  }
				});
			})

			// 添加员工分组
			$(document).on('click','#AddGroup',function(){
				var index = layer.prompt({
				       title : '分组名称：'
				},function(val, index){
				      var data = {
				      	GroupName:val,
				      }
				      $.ajax({
                		type: "POST",
						url:'/customer/add-group-cate',
						data:data,
						dataType: "json",
						success:function (ret) {
			               if(ret.IsBizSuccess){
			               		layer.msg('添加成功');
			               		_this.getGroup();
				     			layer.close(index);
			               }else{
			               		layer.msg('添加失败');
				     			layer.close(index);
			               }
			            }
		        	 })
				});
			})
			// 表格渲染
		    var param = {};
	        var table = $('#datatable').dataTable({
	        	'ordering':false,
	        	"serverSide": true,
	        	"searching":false,
	        	'bLengthChange': false,
	        	"sScrollY" : 562,
	        	ajax: function (data, callback, settings) {
	                param.PageSize = data.length;
	                param.start = data.start;
	                param.PageNo = (data.start / data.length)+1;
	                $.ajax({
	                    type: "POST",
	                    url: "/customer/customer-list",
	                    cache: false,  
	                    data: param,  
	                    dataType: "json",
	                    success: function (result) {
                    	    var returnData = {};
                            returnData.draw = data.draw;
                            returnData.recordsTotal = result.total;
                            returnData.recordsFiltered = result.total;
                            returnData.data = result.data;
                            callback(returnData);
	                    }
	                });
	            },
				"aoColumns":[
					{
			            "mDataProp": "CustomerId",
			            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
			                $(nTd).html('<input type="checkbox" value="" data-id="'+sData+'">');
			            }
			        },
                    {"mDataProp": 'UserRemarkName',
                        "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            var Name = '';
                            if(oData.UserRemarkName){
                                Name = oData.UserRemarkName;
                            }else{
                                Name = oData.UserName;
                            }
                            $(nTd).html(Name);
                        }
                    },
                    {"mDataProp": 'Phone'},
                    {
                    	"mDataProp": 'TagInfoList',
                    	render:function(data){
                    		if(data.length > 0){
                    			var str = '<ul class="ulhistoryTab">';
                    			data.forEach(function(v,k){
                    				str+='<li>'+v.TagName+'</li>'
                    			})
                    			str+='</ul>';
                    			return str;
                    		}else{
                    			return '暂无标签';
                    		}
                    	}
                	},

				],
	        }).api();
	        // 全选
			$(document).on('click','.w-select-all',function(e){
				// 全选
				var _this = $(this);
				$('#datatable tbody input').each(function(k,v){
					if(_this.is(":checked")){
						v.checked = true
					}else{
						v.checked = false
					}
				})
				changeNum();
			})
			// 单个 点击
			$(document).on('click','#datatable tbody input',function(){
				changeNum();
			})
			// 计算 数量
			var changeNum = function(){
				var tot = 0;
				$('#datatable tbody input').each(function(k,v){
					if($(this).is(":checked")){
						tot++;
					}
				})
				$('.chose_count').html(tot);
				if(tot == 0){
					$('.getGroup').attr('disabled',true);
					$(".getGroup option[value='0'] ").attr("selected", true);
				}else{
					$('.getGroup').attr('disabled',false);
				}
			}
			// 左边分组点击
	        $(document).on('click','.getlistid a',function(){
	        	var name = $(this).html();
	        	var index = parseInt($(this).attr('data-index'));
	        	var id = $(this).attr('data-id');
	        	$('.change_tit').html(name);
	        	if(index == 0){
	        		$('.w-btn-group').hide();
	        		$('.btn-movegroup').hide();
	        	}else{
	        		$('.w-btn-group').show();
	        		$('.btn-movegroup').show();
	        	}

	        	$('.chose_count').html(0);
	        	$('.getGroup').attr('disabled',true);
	        	$('.getGroup option').each(function(){
					if(parseInt($(this).val()) == 0){
						$(this).attr('selected',true);
					}else{
						$(this).attr('selected',false);
					}
				})
	        	$('#datatable input').each(function(k,v){
					v.checked = false
				})
	        	param.GroupId = id
	        	table.ajax.reload();
	        })
	        // 重命名 分组名称
			$('.w-ground-rename').click(function(){
				var id = $('.w-tabs-vertical .active a').attr('data-id');
				var index = layer.prompt({
				       title : '填写新名称：'
				},function(val, index){
				      var data = {
				      	GroupName:val,
				      	GroupId:id,
				      }
				      $.ajax({
						url:'/customer/rename-group-cate',
                		type: "POST",
						data:data,
						dataType: "json",
						success:function (ret) {
			               if(ret.IsBizSuccess){
			               		$('.w-tabs-vertical .active a').html(val);
				     			layer.close(index);
			               }else{
			               		layer.msg(ret.ErrMsg);
				     			layer.close(index);
			               }
			            }
		        	 })
				});
			})
			// 删除分组
			$('.w-ground-del').click(function(){
				var id = $('.w-tabs-vertical .active a').attr('data-id');
	        	layer.confirm('是否删除分组？', {
				  btn: ['确定','取消'] //按钮
				}, function(){
				  	$.ajax({
	                    type: "POST",
	                    url: "/customer/customer-delinfo",
	                    data:{GroupId:id,type:100}, 
	                    dataType: "json",
	                    success: function (ret) {
	                	  	if(ret.IsBizSuccess){
				                layer.msg('删除成功');
				                _this.getGroup();
				                $('.w-tabs-vertical li').eq(0).find('a').trigger('click')
	                	  	}else{
	                	  		layer.msg(ret.ErrMsg);
	                	  		return false;
	                	  	}
	                    }
	                });
				});
			})
			// 移动分组 (先移动id 是单个的 接口后续要改)
			$('.getGroup').change(function(e){
				var chosehtml = $(this).children('option:selected').html()
				var GroupId = parseInt($(this).children('option:selected').val());
				if(GroupId == 0){
					layer.msg('请选择分组');
					return false;
				}
				layer.confirm('是否将已选中的客户添加到分组 <span style="color:#ff4c4e;font-size:16px;">'+chosehtml+'</span>', {
				  btn: ['确定','取消'] //按钮
				}, function(){
					MoveGroup(GroupId,100);
					$('.w-select-all').attr('checked',false);
					$('.getGroup').attr('disabled',true);
					$('.getGroup option').each(function(){
						if(parseInt($(this).val()) == 0){
							$(this).attr('selected',true);
						}else{
							$(this).removeAttr('selected');
						}
					})
				},function(){
					$('.getGroup option').each(function(){
						if(parseInt($(this).val()) == 0){
							$(this).attr('selected',true);
						}else{
							$(this).removeAttr('selected');
						}
					})
				});
			})
			// 移动分组 ajax
			var MoveGroup = function(GroupId,type){
				// type  100 移动分组 200 移出分组
				var CustomerIds = []; 
				var data = {
					GroupId:GroupId,
					type:type
				}
				$('#datatable tbody input').each(function(k,v){
					if($(this).is(":checked")){
						var info = $(this).data('id');
						CustomerIds.push(info); //多个
					}
				})
				data.CustomerIds = CustomerIds;
				$.ajax({
	        		type: "POST",
					url:'/customer/move-group-elp',
					data:data,
					dataType: "json",
					success:function (ret) {
		               if(ret.IsBizSuccess){
		               		layer.msg('添加成功');
		               		$('.chose_count').html(0);
		               		table.ajax.reload();
		               }else{
		               		layer.msg(ret.ErrMsg);
		               }
		            }
	        	 })
			}
			// 移出分组
			$('.btn-movegroup').click(function(){
				var num = parseInt($('.chose_count').html());
				if(num == 0){
					layer.msg('请选择要移除的客户');
					return false
				}
				var obj = $('.w-tabs-vertical li.active a');
				var chosehtml = obj.html()
				var GroupId = parseInt(obj.data('id'));
				layer.confirm('是否将已选中的客户从 <span style="color:#ff4c4e;font-size:16px;">'+chosehtml+'</span> 分组移除', {
				  btn: ['确定','取消'] //按钮
				}, function(){
					MoveGroup(GroupId,200);
					$('.w-select-all').attr('checked',false);
					$('.getGroup').attr('disabled',true);
					$('.getGroup option').each(function(){
						if(parseInt($(this).val()) == 0){
							$(this).attr('selected',true);
						}else{
							$(this).removeAttr('selected');
						}
					})
				});
			})
			// 点击选择标签
			$(document).on('click','.Label_btn span',function(){
				if($(this).hasClass('E8ECEE')){
                    $(this).removeClass('E8ECEE')
                }else{
                    $(this).addClass('E8ECEE')
                }
			})
			// 选择完成
			$('.choseOk').click(function(){
					var str = ''
	                var TagIds = [];
	                $('.Label_btnspan.E8ECEE').each(function(k,v){
	                    var id = $(this).data('id')
	                    var name = $(this).data('name')
	                    TagIds.push(id);
	                    str +='<li data-id="'+v.id+'">'+name+'</li>'
	                })
	                _this.TagIds = TagIds;
	                $('.edit_sign').html(str+'<div class="edit_gochose" data-toggle="modal" data-target="#custom-width-modal">添加标签</div>');
					$('#custom-width-modal').modal('hide');
			})
			// 点击添加客户
	        $('.add_client').click(function(){
	        	setTimeout(function(){
	        		$('.modal-backdrop').css({'z-index':21})
	        		$('#con-close-modal').css('z-index',22)
	        	},100)
	        	$('.UserRemarkName').val('')
	        	$('.PhoneInfo').val('')
	        	$('#chose_group option').each(function(){
	        		if(parseInt($(this).val()) == 0){
	        			$(this).attr('selected','selected');
	        		}else{
	        			$(this).removeAttr('selected');
	        		}
	        	})
	        	$('#Sex option').each(function(){
	        		if(parseInt($(this).val()) == -1){
	        			$(this).attr('selected','selected');
	        		}else{
	        			$(this).removeAttr('selected');
	        		}
	        	})
	        	$('.Email').val('')
	        	$('.Address').val('')
	        	$('.Birthday').val('')
	        	$('.Remark').val('')
	        	$('.edit_sign').html('<div class="edit_gochose" data-toggle="modal" data-target="#custom-width-modal">选择标签</div>');
	        	$('.Label_btn span').removeClass('E8ECEE');
	        })
	        //  添加按钮
	        $('.edit_userinfo').click(function(){
	        	var $this = $(this);
	        	var data = {
	        		UserName:$('.UserRemarkName').val(),
                    Phone:$('.PhoneInfo').val(),
                    GroupId:parseInt($('#chose_group option:selected').val()),
                    Sex:parseInt($('#Sex option:selected').val()),
                    Email:$('.Email').val(),
                    Address:$('.Address').val(),
                    Birthday:$('.Birthday').val(),
                    Remark:$('.Remark').val(),
                    TagIds:_this.TagIds, 
                    type:200,
                }
	        	$.ajax({
                    type: "POST",
                    url: "/customer/customer-editinfo",
                    data:data, 
                    dataType: "json",
                    success: function (ret) {
                	  	if(ret.IsBizSuccess){
			                layer.msg('添加成功');
                	  		$('#con-close-modal').modal('hide');
                	  		table.ajax.reload();
                	  	}else{
                	  		layer.msg(ret.ErrMsg);
                	  		return false;
                	  	}
                    }
                });
	        })













		}
	}
	var a = new Cont();

})